package org.example.service;

import com.mongodb.client.*;
import org.bson.Document;
import org.example.util.DBUtil;

public class LoginService {
    MongoDatabase mongoDatabase=DBUtil.getMongoClient().getDatabase("TouHouGame");
    public LoginService(){}

    public String UserLogin(String user,String password){
        MongoCollection<Document> users=mongoDatabase.getCollection("users");
        Document comm=new Document("user",user);
        FindIterable<Document> results=users.find(comm);
        MongoCursor<Document> cursorIterator = results.cursor();
        while (cursorIterator.hasNext()) {
            Document document = cursorIterator.next();
            if(document.get("password").equals(password)){
                return "success";
            }else{
                return "password error";
            }
        }
        return "user unregistered";
    }

    public String UserSignIn(String user,String password){
        MongoCollection<Document> users=mongoDatabase.getCollection("users");
        Document comm=new Document("user",user);
        FindIterable<Document> results=users.find(comm);
        MongoCursor<Document> cursorIterator = results.cursor();
        while (cursorIterator.hasNext()) {
            return "user exists";
        }
        Document user_doc=new Document();
        user_doc.put("user",user);
        user_doc.put("password",password);
        users.insertOne(user_doc);
        return "success";
    }
}
